
package nachos.network;

import nachos.threads.*;

import java.util.*;

/**
 * Thread that handles sending <tt>MailMessage</tt>s.  
 */
public class SendThread 
   extends KThread implements TimerListener {

   private SendRunner runner = null;
   //(KYLE) I don't think this needs to be threadsafe because it's only
   //       accessed by this thread
   private LinkedList<MailMessage> messagesToSend = new LinkedList<MailMessage>();

   public SendThread() {
      super( );
      runner = new SendRunner( this );
      setTarget( runner );
   }

   public void stop() {
      runner.stop();
   }

   public void handleTimer( int tick ) {
      //System.out.println( "SendThread got tick: " + tick );
   }

   public void add( MailMessage message )
   {
      messagesToSend.add(message);
   }

   public void sendMessageFromBuffer() {
       MailMessage msg = messagesToSend.poll();
       if(msg != null)
       {
          //System.out.println( "Sending MailMessage: " + msg );
          NetKernel.getPostOffice().send(msg);
       }
   }

}

class SendRunner implements Runnable {
   private boolean shouldRun = true;
   public SendThread sendThread = null;
   public SendRunner( SendThread sendThread ) {
      this.sendThread = sendThread;
   }
   public void stop() {
      shouldRun = false;
   }
   public void run() {
      while( shouldRun ) {
         sendThread.sendMessageFromBuffer();
         KThread.yield();
      }
   }
}
